package com.ywu.file.sys.sdk.enter;

import com.ywu.file.sys.sdk.utils.YfsBuildMssaHeaderUtil;
import com.ywu.file.sys.sdk.utils.YfsRestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName YwuFileSysExec
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/9/28 8:31
 * @Version 1.0
 **/
@Component
@Slf4j
public class YwuFileSysExec {
    private static final String AUTH_TOKEN_HEADER_KEY = "AuthToken";

    @Autowired
    private YfsBuildMssaHeaderUtil buildMssaHeaderUtil;

    @Autowired
    private YfsRestTemplateUtil restTemplateUtil;

    /**
    * @Author GroundDemo
    * @Description 上传文件
    * @Date 11:38 2024/9/28
    * @Param [file, isShare]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public Map<String, String> upload(File file, boolean isShare) {
        Map<String, String> res = new HashMap<>();
        // 构建请求cookie
        String authToken = buildMssaHeaderUtil.buildAuthToken();
        if (StringUtils.isEmpty(authToken)) {
            res.put("code", "400");
            return res;
        }
        // 构建参数
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put(AUTH_TOKEN_HEADER_KEY, authToken);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        FileSystemResource fileSource = new FileSystemResource(file);
        form.add("file", fileSource);
        form.add("isShare", isShare);
        String resUrl = restTemplateUtil.execUpload(headerMap, form);
        if (StringUtils.isEmpty(resUrl)) {
            res.put("code", "400");
            return res;
        }
        res.put("code", "200");
        res.put("fileUrl", resUrl);
        return res;
    }

    /**
    * @Author GroundDemo
    * @Description 下载文件
    * @Date 13:45 2024/10/11
    * @Param [fileId]
    * @return java.lang.String
    **/
    public String download(String fileId) {
        // 构建请求cookie
        String authToken = buildMssaHeaderUtil.buildAuthToken();
        if (StringUtils.isEmpty(authToken)) {
            log.error("build token error");
            return null;
        }
        // 构建参数
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put(AUTH_TOKEN_HEADER_KEY, authToken);
        return restTemplateUtil.execDownload(headerMap, fileId);
    }
}
